import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver, NaiveUiResolver } from 'unplugin-vue-components/resolvers'
import VueSetupExtend from "vite-plugin-vue-setup-extend";
import Components from 'unplugin-vue-components/vite'
import px2rem from "postcss-px2rem"

export default (({ mode }) => {
  // https://vitejs.dev/config/
  //https://blog.csdn.net/qq_45429889/article/details/124837035
  const VITE_APP_BASE_API: string = loadEnv(mode, process.cwd()).
    VITE_APP_BASE_API;
  return defineConfig({
    build: {
      chunkSizeWarningLimit: 1500,
      rollupOptions: {
        output: {
          // 分包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id
                .toString()
                .split('node_modules/')[1]
                .split('/')[0]
                .toString()
            }
          }
        }
      }
    },
    plugins: [
      vue(),
      VueSetupExtend(),
      createSvgIconsPlugin({
        // Specify the icon folder to be cached
        iconDirs: [path.resolve(process.cwd(), 'src/icons')],
        // Specify symbolId format
        symbolId: 'icon-[dir]-[name]',
        /**
           * custom dom id
           * @default: __svg__icons__dom__
           */
        customDomId: '__svg__icons__dom__'
      }),
      AutoImport({
        // resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [
          ElementPlusResolver(), NaiveUiResolver() // naive 和 element plus
        ]
      })
    ],
    base: './',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, 'src'),
        '@assets': path.resolve(__dirname, 'src/assets'),
        '@components': path.resolve(__dirname, 'src/components'),
        '@composables': path.resolve(__dirname, 'src/composables')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/scss/globalVariable.scss";'
        },
      },
      postcss: {
        plugins: [
          px2rem({
            remUnit: 192
          })
        ],
      }
    },
    server: {
      host: '0.0.0.0',
      port: 10086,
      open: false,
      cors: true,
      proxy: {
        '/api': {
          target: VITE_APP_BASE_API,
          changeOrigin: true,
          ws: true,
          rewrite: (path) => path.replace(/^\/api/, '/rcss') // 将api替换为空
        }
      }
    }
  })
})

